package cn.zwx.member.svc.utils;

import cn.zwx.base.exception.BizWrapException;
import cn.zwx.member.svc.domain.enums.MemberCodeEnum;
import cn.zwx.member.svc.domain.warp.ExceptionWrap;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Base64;

/**
 * @author zhangwenxue
 */
public class SaltUtil {

    private static final int ITERATIONS = 10000;
    private static final int KEY_LENGTH = 256;
    private static final String ALGORITHM = "PBKDF2WithHmacSHA256";



    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    public static String hashPassword(String password, String salt) throws BizWrapException {
       KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), ITERATIONS, KEY_LENGTH);
        byte[] hash;
        try {
           SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
            hash = factory.generateSecret(spec).getEncoded();
       }catch (Exception e){
            throw ExceptionWrap.wrap(MemberCodeEnum.GENERATE_PASSWORD_ERROR);
       }
        return Base64.getEncoder().encodeToString(hash);
    }

    public static boolean verifyPassword(String password, String salt, String hashedPassword) throws BizWrapException {
        String calculatedHash = hashPassword(password, salt);
        return calculatedHash.equals(hashedPassword);
    }

}
